<template>
  <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
  >
    <el-form-item label="账号：" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="密码：" prop="password">
      <el-input v-model="ruleForm.password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup>
import {ref } from 'vue'
import {loginUser} from "@/api/login.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";


const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = ref({
  username: '',
  password:'',
})



const rules = ref({
  username: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ]
})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loginUser(ruleForm.value).then((res)=>{
        if (res.data.code==200){
          ElMessage.success("登录成功")
          localStorage.setItem("token",res.data.data)
          router.push("/main")
        }else {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}


</script>